from rest_framework import serializers
from .models import Suite, RunResult, SuiteExecutionRecord

class SuiteExecutionRecordSerializer(serializers.ModelSerializer):
    class Meta:
        model = SuiteExecutionRecord
        fields = ['id', 'suite', 'status', 'result', 'report_url', 'executed_cases', 'created_at', 'updated_at']

class SuiteSerializer(serializers.ModelSerializer):
    case_count = serializers.SerializerMethodField()
    project_name = serializers.CharField(source='project.name', read_only=True)
    cases = serializers.PrimaryKeyRelatedField(source='case_api_list', many=True, read_only=True)
    latest_execution = serializers.SerializerMethodField()
    
    class Meta:
        model = Suite
        fields = ['id', 'name', 'description', 'status', 'project', 'project_name', 'case_api_list', 
                 'cases', 'case_count', 'created_time', 'updated_time', 'latest_execution']
        read_only_fields = ['project_name', 'cases', 'case_count', 'created_time', 'updated_time', 'latest_execution']
    
    def get_case_count(self, obj):
        return obj.case_api_count()
    
    def get_latest_execution(self, obj):
        record = obj.executions.first()
        if record:
            return SuiteExecutionRecordSerializer(record).data
        return None
        return obj.case_api_count()
    
    def create(self, validated_data):
        cases = validated_data.pop('case_api_list', [])
        suite = Suite.objects.create(**validated_data)
        if cases:
            suite.case_api_list.set(cases)
        return suite


class RunResultSerializer(serializers.ModelSerializer):
    status_display = serializers.CharField(source='get_status_display', read_only=True)
    
    class Meta:
        model = RunResult
        fields = ['id', 'suite', 'project', 'path', 'is_pass', 'status', 'status_display']
        read_only_fields = ['status_display']
